package net.tv90.volunteerserveradmin.service;

import jakarta.annotation.Resource;
import net.tv90.volunteerserveradmin.dao.ProjectTeacherRelationRepository;
import net.tv90.volunteerserveradmin.dao.TeacherRepository;
import net.tv90.volunteerserveradmin.dao.VolunteerProjectRepository;
import net.tv90.volunteerserveradmin.exception.ServiceException;
import net.tv90.volunteerserveradmin.model.domain.ProjectTeacherRelation;
import net.tv90.volunteerserveradmin.model.domain.VolunteerProject;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProjectTeacherRelationService {

    @Resource
    private ProjectTeacherRelationRepository projectTeacherRelationRepository;
    @Resource
    private VolunteerProjectRepository volunteerProjectRepository;
    @Resource
    private TeacherRepository teacherRepository;

    /**
     * 教师添加项目
     *
     * @param teacherId 教师ID
     * @param projectId 项目ID
     * @throws ServiceException 如果教师已负责该项目，则抛出异常
     */
    public void addProjectToTeacher(Long teacherId, Long projectId) throws ServiceException {
        // 检查该教师是否已负责该项目
        if (projectTeacherRelationRepository.existsByTeacherIdAndProjectId(teacherId, projectId)) {
            throw new ServiceException("教师已负责该项目，无法重复添加");
        }

        // 创建新的关联记录
        ProjectTeacherRelation relation = new ProjectTeacherRelation();
        relation.setTeacherId(teacherId);
        relation.setProjectId(projectId);

        // 保存教师与项目的关系
        projectTeacherRelationRepository.save(relation);
    }

    /**
     * 教师删除项目
     *
     * @param teacherId 教师ID
     * @param projectId 项目ID
     * @throws ServiceException 如果教师没有负责该项目，则抛出异常
     */
    public void removeProjectFromTeacher(Long teacherId, Long projectId) throws ServiceException {
        // 查找教师与项目的关联关系
        ProjectTeacherRelation relation = projectTeacherRelationRepository.findByTeacherIdAndProjectId(teacherId, projectId);
        if (relation == null) {
            throw new ServiceException("教师未负责该项目，无法删除");
        }

        // 删除教师与项目的关系
        projectTeacherRelationRepository.delete(relation);
    }

    /**
     * 获取教师负责的所有项目
     *
     * @param teacherId 教师ID
     * @return 教师负责的所有项目的ID列表
     * @throws ServiceException 如果教师没有负责任何项目，则抛出异常
     */
    public List<Long> getTeacherProjects(Long teacherId) throws ServiceException {
        // 获取教师负责的所有项目
        List<ProjectTeacherRelation> relations = projectTeacherRelationRepository.findByTeacherId(teacherId);

        // 如果教师没有负责任何项目，抛出异常
        if (relations.isEmpty()) {
            throw new ServiceException("教师没有负责任何项目");
        }

        // 返回项目ID列表
        return relations.stream().map(ProjectTeacherRelation::getProjectId).toList();
    }

    public List<String> getProjectsByTeacherId(Long teacherId) throws ServiceException {
        // 获取教师与项目的关联记录
        List<ProjectTeacherRelation> relations = projectTeacherRelationRepository.findByTeacherId(teacherId);

        if (relations.isEmpty()) {
            throw new ServiceException("教师没有负责任何项目");
        }

        // 根据关联记录中的项目ID，获取项目的详细信息
        List<Long> projectIds = relations.stream()
                .map(ProjectTeacherRelation::getProjectId) // 获取所有的项目ID
                .collect(Collectors.toList());

        // 获取这些项目的名称（或其他需要的字段）
        List<VolunteerProject> projects = volunteerProjectRepository.findAllById(projectIds);

        return projects.stream()
                .map(VolunteerProject::getTitle) // 获取项目的名称
                .collect(Collectors.toList());
    }

    public void teacherSelectProject(Long teacherId, Long projectId) throws ServiceException {
        // 检查该教师是否已选择该项目
        if (projectTeacherRelationRepository.existsByTeacherIdAndProjectId(teacherId, projectId)) {
            throw new ServiceException("教师已负责该项目，无法重复选择");
        }
        // 检查项目是否存在
        VolunteerProject volunteerProject = volunteerProjectRepository.findById(projectId)
                .orElseThrow(() -> new ServiceException("志愿项目不存在！"));
        // 检查项目是否允许新增负责教师（可根据业务需求限制多个教师负责同一项目）
        if (volunteerProject.getMaxTeacherNum() != null &&
                projectTeacherRelationRepository.countByProjectId(projectId) >= volunteerProject.getMaxTeacherNum()) {
            throw new ServiceException("该项目的负责教师人数已达到上限！");
        }
        // 检查项目状态（例如，已结束的项目无法添加教师）
        if (volunteerProject.getStatus() != 0) {
            throw new ServiceException("该项目已开始或已结束，无法选择！");
        }
        // 创建教师与项目的关系
        ProjectTeacherRelation relation = new ProjectTeacherRelation();
        relation.setTeacherId(teacherId);
        relation.setProjectId(projectId);
        // 保存关系
        projectTeacherRelationRepository.save(relation);
    }


    public void teacherQuitProject(Long teacherId, Long projectId) throws ServiceException {
        // 检查教师与项目的关系是否存在
        ProjectTeacherRelation relation = projectTeacherRelationRepository
                .findByTeacherIdAndProjectId(teacherId, projectId);
        // 检查项目状态（例如，已开始或已结束的项目可能无法退选）
        VolunteerProject volunteerProject = volunteerProjectRepository.findById(projectId)
                .orElseThrow(() -> new ServiceException("志愿项目不存在！"));
        if (volunteerProject.getStatus() != 0) {
            throw new ServiceException("该项目已开始或已结束，无法退选！");
        }
        // 删除教师与项目的关系
        projectTeacherRelationRepository.delete(relation);
    }

}
